<template>
    <!-- 查询区域 -->
    <a-row type="flex" justify="center" align="middle" style="min-height: 100vh">
        <a-col span="8">
            <a-form ref="formRef" :model="user" :label-col="labelCol" :wrapper-col="wrapperCol" @finish="onFinish" :rules="userRules"
                @finishFailed="onFinishFailed">
                <a-form-item label="账号" name="username">
                    <!--修改用户时,账号不能修改-->
                    <a-input v-model:value="user.username" />
                </a-form-item>
                <a-form-item label="姓名" name="name">
                    <a-input v-model:value="user.name" />
                </a-form-item>
                <a-form-item label="密码" name="password">
                    <a-input-password v-model:value="user.password" />
                </a-form-item>
                <a-form-item label="重复密码" name="matchingPassword">
                    <a-input-password v-model:value="user.matchingPassword" />
                </a-form-item>
                <a-form-item label="邮箱" name="email">
                    <a-input v-model:value="user.email" />
                </a-form-item>
                <a-form-item label="手机" name="mobile">
                    <a-input v-model:value="user.mobile" />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                    <a-button type="primary" html-type="submit">保存</a-button>
                </a-form-item>
            </a-form>

        </a-col>
    </a-row>
</template>
   
<script lang="ts" setup>
import {
    ref,
    reactive,
    onMounted,
    Ref
} from "vue";
import type { UnwrapRef } from 'vue';
import { message, Form } from 'ant-design-vue';
import http from '@/utils/http';
import type { Data } from '@/utils/http';
import _ from 'lodash';



/**
 * 用户对象数据类型定义
 * id 
 * name 姓名
 * username 账号
 * email 邮箱
 * mobile 手机
 * enabled 是否激活，默认激活
 * accountNonExpired 账户是否未过期，默认未过期
 * accountNonLocked  账户是否未锁定，默认未锁定
 * credentialsNonExpired 密码是否未过期，默认未过期
 */
interface FormState {
    name: string;
    username: string;
    email: string;
    mobile: string;
    password: string;
    matchingPassword: string;
}

/******新增用户*********/
//form中label宽度
const labelCol = { style: { width: '150px' } };
const wrapperCol = { span: 14 };
const formRef = ref();


//用户对象数据变量定义
const user: UnwrapRef<FormState> = reactive({
    name: "",
    username: "",
    email: "",
    mobile: "",
    password: "",
    matchingPassword: ""
});

//form的校验规则
const userRules = {
    name: [
        {
            required: true,
            message: "用户名为必填项！",
            trigger: "blur",
        },
        {
            max: 20,
            message: "用户名长度不得超过20！",
            trigger: "blur",
        },
    ],
    username: [
        {
            required: true,
            message: "用户账号为必填项！",
            trigger: "blur",
        },
        {
            max: 20,
            message: "用户账号长度不得超过20！",
            trigger: "blur",
        },
        {
            // 异步验证 多了一个callback函数
            validator: (rule: any, val: any, callback: any) => {

                if (val.length > 0) {
                    const usernameParam = {
                        username: val
                    };
                    // 这里进行异步操作,下面以promise举例
                    http.get('/authorize/validateUsername', usernameParam).then((res) => {
                        if (res.data.status === "success") {
                            callback()
                        }
                        else {
                            callback(new Error('用户账号不能重复'))
                        }
                    })
                } else {
                    callback()
                }
            },
            trigger: "blur"
        }
    ],
    // 最少 8 个、最多 10 个字符，至少 1 个大写字母、1 个小写字母、1 个数字和 1 个特殊字符:
    // "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,10}$"
    password: [
        {
            required: true,
            message: "用户密码为必填项！",
            trigger: "blur",
        },
        {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\\-_@$!%*?&])[A-Za-z\d\\-_@$!%*?&]{8,16}$/,
            message: '最少 8 个、最多 16 个字符，至少 1 个大写字母、1 个小写字母、1 个数字和 1 个特殊字符:',
            trigger: "blur",
        },
    ],
    matchingPassword: [
        {
            required: true,
            message: "重复密码为必填项！",
            trigger: "blur",
        },
        {
            // 异步验证 多了一个callback函数
            validator: (rule: any, val: any, callback: any) => {
                if (formRef.value.getFieldsValue().password === val) {
                    callback();
                } else {
                    callback(new Error('两次输入密码不一致'));
                }

            },
            trigger: "blur"
        }
    ],
    email: [
        {
            required: true,
            message: "邮箱为必填项！",
            trigger: "blur",
        },
        {
            pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            message: '邮箱格式不正确',
            trigger: "blur",
        },
        {
            // 异步验证 多了一个callback函数
            validator: (rule: any, val: any, callback: any) => {

                if (val.length > 0) {
                    const emailParam = {
                        email: val
                    };
                    // 这里进行异步操作,下面以promise举例
                    http.get('/authorize/validateEmail', emailParam).then((res) => {
                        if (res.data.status === "success") {
                            callback()
                        }
                        else {
                            callback(new Error('邮箱不能重复'))
                        }
                    })
                } else {
                    callback()
                }
            },
            trigger: "blur"
        }
    ],
    mobile: [
        {
            required: true,
            message: "手机为必填项！",
            trigger: "blur",
        },
        {
            pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
            message: '请输入正确手机号',
            trigger: "blur",
        },
        {
            // 异步验证 多了一个callback函数
            validator: (rule: any, val: any, callback: any) => {

                if (val.length > 0) {
                    const mobileParam = {
                        mobile: val
                    };
                    // 这里进行异步操作,下面以promise举例
                    http.get('/authorize/validateMobile', mobileParam).then((res) => {
                        if (res.data.status === "success") {
                            callback()
                        }
                        else {
                            callback(new Error('手机号码不能重复'))
                        }
                    })
                } else {
                    callback()
                }
            },
            trigger: "blur"
        }
    ]
};

//重置用户对象数据
const clearUser = () => {
    user.name = "";
    user.username = "";
    user.email = "";
    user.mobile = "";
    user.password = "";
    user.matchingPassword = "";
};



//校验成功后提交form
const onFinish = (values: any) => {
    const url = '/authorize/register';
    http.post(url, user).then((res) => {
        if (res.data.status === "success") {
            message.success("注册成功!");
        }
        else {
            const errLen = res.data.businessData.errMsgList.length;
            message.error(res.data.businessData.errMsgList[0]);
            let n = 1;
            const messageInterval = setInterval(function () {

                if (n < errLen) {
                    message.error(res.data.businessData.errMsgList[n]);
                    n++;
                } else {
                    //
                    clearInterval(messageInterval);
                }
                //时间与后端token失效时间相同
            }, 1000);
        }
    });

};

const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
};
/******新增用户结束*********/


//   //页面加载完成后，刷新第一页数据
onMounted(() => {
    clearUser();
});

</script>
<style scoped>
/*[data-doc-theme='light'] */
.ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
}

[data-doc-theme='dark'] .ant-table-striped :deep(.table-striped) td {
    background-color: rgb(29, 29, 29);
}
</style>